package org.dtc.geo.picture;

import com.google.common.collect.ImmutableMap;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

/**
 * @author zhouyu
 * @create 2024-01-08 9:32
 */
public class Browser {

    private ChromeDriver webDriver;

    public Browser() {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--mute-audio");
        chromeOptions.addArguments("--remote-allow-origins=*");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-web-security");
        chromeOptions.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
        chromeOptions.setExperimentalOption("useAutomationExtension", false);
        // chromeOptions.addArguments("--blink-settings=imagesEnabled=false")
        chromeOptions.addArguments(
                "--ignore-certificate-errors",
                "--ignore-ssl-errors",
                "--ignore-ssl-error",
                "--ignore-certificate-errors-spki-list"
        );

        // chromeOptions.addArguments('--proxy-server=http://a901.kdltps.com:15818')
        chromeOptions.addArguments(String.format("--user-agent=%s", UserAgentUtil.randomUserAgent()));
        this.webDriver = new ChromeDriver(chromeOptions);
        this.webDriver.manage().window().setSize(new Dimension(1920, 1080));
        this.webDriver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(60));
        //不设置隐式等待
        this.webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        this.webDriver.executeCdpCommand(
                "Page.addScriptToEvaluateOnNewDocument",
                ImmutableMap.of("source",
                        "Object.defineProperty(navigator, 'webdriver', { get: () => undefined})"
                )
        );
    }

    public void getUrl(String url) {
        webDriver.get(url);
    }

    public WebElement findElement(By locator) {
        return webDriver.findElement(locator);
    }

    public List<WebElement> findElements(By locator) {
        return webDriver.findElements(locator);
    }
}
